using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using Deepcode.Flux.Core.Data;
using Deepcode.Flux.Core.Systems.Security;
using Deepcode.Flux.Core.Services.State;
using Deepcode.Flux.Core.Systems.Audit.Quick;

public partial class Private_Config_Users_listWindows : Deepcode.Flux.Core.UI.AdministrationModulePage
{
	#region Permission Code Override
	public override string RequiredPermissionCode { get { return "FluxSecUsers"; } }
	#endregion
	#region Page Load event
	/// <summary>
	/// Page Load event
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	protected void Page_Load(object sender, EventArgs e)
	{
		if (!Page.IsPostBack)
		{
			LoadState();
			BindDataGrid();
		}
	}
	#endregion
	#region Initialisation
	/// <summary>
	/// OnInit - hooks up the data paging handler, 
	/// rpp change handler and item command handlers
	/// </summary>
	/// <param name="e"></param>
	protected override void OnInit(EventArgs e)
	{
		base.OnInit(e);
		datapager.OnRepage += new Deepcode.Flux.Core.UI.Controls.DataPager.PagerRepage(BindDataGrid);
		datapager.OnRPPChanged += new Deepcode.Flux.Core.UI.Controls.DataPager.RPPChanged(RowsPerPageChange);
		datagrid.ItemCommand += new DataGridCommandEventHandler(GridCommand);
		datagrid.SortDirectionCommand += new Deepcode.Flux.Core.UI.Controls.StandardDataGrid.OnSortDirectionCommand(GridSortDirection);
		// Add sort commands
	}
	#endregion
	#region Data binding and paging events
	/// <summary>
	/// Data binding
	/// </summary>
	private void BindDataGrid()
	{
		// Add javascript call to delete buttons
		datagrid.BindJavascript("btnDelete", "onclick", "return ConfirmDelete();");
		// Set rows per page from registry
		datapager.RowsPerPage = this.UserSetting("RowsPerPage", 10);
	
		// Get and bind the data
		AdministrationUsers users = new AdministrationUsers();
		datapager.DataSource = users.GetAllUsers(this.CurrentSortOrder, this.CurrentSortDirection);
		datapager.DataBind();
	}
	/// <summary>
	/// Paging control has set a new number of rows per page - store in user registry
	/// </summary>
	/// <param name="NewRPP"></param>
	void RowsPerPageChange(int NewRPP)
	{
		this.SetUserSetting("RowsPerPage", NewRPP);
	}
	#endregion
	#region User interactions
	/// <summary>
	/// Command received from the data grid
	/// </summary>
	/// <param name="source"></param>
	/// <param name="e"></param>
	void GridCommand(object source, DataGridCommandEventArgs e)
	{
		if( e.Item.ItemType == ListItemType.Footer ||
			e.Item.ItemType == ListItemType.Header ||
			e.Item.ItemType == ListItemType.Pager ||
			e.Item.ItemType == ListItemType.Separator ) return;

		// Get the key of the row being actioned 
		int rowKey = (int) datagrid.DataKeys[e.Item.ItemIndex];

		// PROCESS COMMANDS
		if( e.CommandName == "Delete" )
		{
			AdministrationUsers users = new AdministrationUsers();
			AdministrationUser u = users.GetUserByID( rowKey );
			users.DeleteByID( rowKey );
						
			QuickAudit.RaiseImportant(
				new AuditUser(),
				"Flux", "User manager",
				"deleted user {0} ({1} {2})",
				u.PK_ID, u.RealName, u.EMailAddress);

			this.BindDataGrid();
			return;
		}
		if( e.CommandName == "Edit" )
		{
			string url = String.Format("ui_formWindows.aspx?ID={0}&state={1}", rowKey, this.SaveState());
			Response.Redirect( url, true );
			return;
		}
	}
	/// <summary>
	/// User clicked the add new button
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	protected void btnAddNew_Click(object sender, EventArgs e)
	{
		string url = String.Format("ui_formWindows.aspx?state={0}", this.SaveState());
		Response.Redirect(url, true);
	}
	#endregion
	#region State Remember/Recall
	/// <summary>
	/// Load current state from a string on the url
	/// </summary>
	private void LoadState()
	{
		StateRemember r = new StateRemember(Request["state"]);
		datapager.StartRow = r.Recall("StartRow", 1);
		CurrentSortOrder = (AdministrationUsersSortOrder)r.Recall("SortOrder", AdministrationUsersSortOrder.EmailAddress);
		CurrentSortDirection = (DataSortDirection)r.Recall("SortDirection", DataSortDirection.ASCENDING);
		datagrid.CurrentSortDirection = CurrentSortDirection;
		datagrid.CurrentSort = CurrentSortOrder.ToString();
	}
	/// <summary>
	/// Save current state to a string for later recall
	/// </summary>
	/// <returns></returns>
	public string SaveState()
	{
		StateRemember r = new StateRemember();
		r.Remember("StartRow", datapager.StartRow);
		r.Remember("SortOrder", CurrentSortOrder);
		r.Remember("SortDirection", CurrentSortDirection);
		return r.ToString();
	}
	#endregion

	#region ViewState storage
	/// <summary>
	/// Stores the current sort order in the viewstate
	/// </summary>
	public AdministrationUsersSortOrder CurrentSortOrder
	{
		get
		{
			object o = ViewState["CurrentSortOrder"];
			if (o == null) return AdministrationUsersSortOrder.EmailAddress;
			return (AdministrationUsersSortOrder)o;
		}
		set
		{
			ViewState["CurrentSortOrder"] = value;
		}
	}
	/// <summary>
	/// Stores the current sort direction
	/// </summary>
	public DataSortDirection CurrentSortDirection
	{
		get
		{
			object o = ViewState["CurrentSortDirection"];
			if (o == null) return DataSortDirection.ASCENDING;
			return (DataSortDirection)o;
		}
		set
		{
			ViewState["CurrentSortDirection"] = value;
		}
	}
	#endregion
	#region Sorting
	/// <summary>
	/// User has changed the sort direction or sort order
	/// </summary>
	/// <param name="source"></param>
	/// <param name="SortExpression"></param>
	/// <param name="Direction"></param>
	void GridSortDirection(object source, string SortExpression, DataSortDirection Direction)
	{
		this.CurrentSortDirection = Direction;

		switch (SortExpression)
		{
			case "RealName":
				this.CurrentSortOrder = AdministrationUsersSortOrder.RealName;
				break;
			case "NT_Username":
				this.CurrentSortOrder = AdministrationUsersSortOrder.NT_Username;
				break;
			case "EmailAddress":
			default:
				this.CurrentSortOrder = AdministrationUsersSortOrder.EmailAddress;
				break;
		}
		this.BindDataGrid();
	}
	#endregion
}
